<?php
namespace app\common\service;

use app\index\model\ZhiniaoUserModel;
use app\wechat\service\WechatService;

class UserService{


    // 用户扫码绑定微信
    public function bindUser($data){

        $uid = $data['uid'] ?? 0;
        $openid = $data['openid'] ?? 0;
        if(!$uid){
            return '绑定失败，用户ID有误，请联系管理员';
        }
        if(!$openid){
            return '微信openid有误，绑定失败，请联系管理员';
        }
        $user = ZhiniaoUserModel::find($uid);
        if(!$user){
            return '绑定用户不存在，请重新登录后重试绑定。';
        }
        if($user['openid']){
            return '当前账户已绑定过微信，无需再次绑定';
        }
        $user->openid = $openid;
        $user->save();
        return '绑定成功';
    }


    public static function userLoginCache($user){
        $username = $user['username'];
        $token = md5($username . time());
        $data = [
            'token' => $token
        ];
        cache($token, [
            'user' => $user,
            'username' => $username,
            'avatar' => [
                'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif'
            ],
            'permissions' =>  explode(',', $user['role']),      
        ], 60 * 60 * 24);
        return $data;
    }


    // 微信回调。
    public function wechatLogin($data){
        $openid = $data['openid'] ?? 0;
        $login_key = $data['login_key'] ?? '';

        if(!$openid){
            return '微信openid有误，请联系管理员';
        }
        $user = ZhiniaoUserModel::where(['openid' => $openid])->find();
        
        if($user){
            $login_data = $this->userLoginCache($user);
            cache($login_key, $login_data, 60 * 60 * 24);
            WechatTemplate::sendLoginSuccessTemp($user);
            return false;
        }else{
            return '当前微信暂未绑定账户，请绑定后重试扫码登录功能';
        }
    }


}